package com.sun.dream.fish.config.shiro;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sun.dream.fish.entity.TRoleEntity;
import com.sun.dream.fish.entity.TUserEntity;
import com.sun.dream.fish.service.TRoleService;
import com.sun.dream.fish.service.TUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Description:  实现自定义realm
 * Created By ljl on 2023/12/11.
 */
@Slf4j
public class DSFRealm extends AuthorizingRealm {
    @Autowired
    TUserService userService;
    @Autowired
    TRoleService roleService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        TUserEntity principal = (TUserEntity) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        TRoleEntity roleEntity = roleService.getById(principal.getRoleId());
        info.addRole(roleEntity.getName());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userInfo = (UsernamePasswordToken) token;
        LambdaQueryWrapper<TUserEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(TUserEntity::getUsername, userInfo.getUsername()).or()
                .eq(TUserEntity::getTelephone, userInfo.getUsername());
        TUserEntity user = userService.getOne(queryWrapper);
        if (user == null) {
            log.warn("[用户信息认证],未查询到该用户信息,用户名: {}", userInfo.getUsername());
            return null;
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}
